package civicinity.ist.psu.edu.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.util.Log;
import civicinity.ist.psu.edu.constants.Constants;

/**
 * This class is for storing the functions that accessed by several different activities.
 * @author kyunghan
 *
 */
public class CivicinityHelpers {

	/**
	 * If necessary, manually revise the PubDate value and convert into Unix time frame. 
	 * @param pubDate
	 * @return
	 */
	public String convertDateFormatRSS(String pubDate) {
		// Do some special if-else condition on the "pub date".
		// since each rss has a different value on each date,
		// make this value into the same format (milliseconds)
		// If no pubdate field is provided, just ignore this.
		// format : Tue, 09 Jan 2002 22:14:02 -0500
		String getPubDate = pubDate;
		
		//Log.i("K", "---------pubDate : " + pubDate);
		
		String []finalPubDateArr = {"Mon", "01", "Jan", "2000", "12:00:00"};
		
		// if it is null, assign random value.
		if(getPubDate.equals(null)) {
			getPubDate = "Mon, 20 Jan 2000 12:00:00 -0400"; 
		}
	
		String[] splitPubDate = getPubDate.split(" ");
		CivicinityHelpers cHelper = new CivicinityHelpers();
		
		for(int k = 1 ; k < splitPubDate.length ; k++) {
			if(k >= 1 && k <= 4) {
				finalPubDateArr[k] = cHelper.checkFormat(splitPubDate[k], k);
			}
		}
		
		String finalPubDateStr = finalPubDateArr[1] + " " + finalPubDateArr[2] + " " + finalPubDateArr[3] + " " + finalPubDateArr[4];
			    			
		//Log.i("K", "finalPubDate : " + finalPubDateStr);
		
		SimpleDateFormat formatter = null;
		formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
		
		if(finalPubDateStr.contains("2000")) {
			Log.i("K", "return 'bad value' on Pubdate");
			return "bad value";
		}
		
		Date date = null;
		try {
			date = formatter.parse(finalPubDateStr.trim());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "bad value";
		}
		
		return String.valueOf(date.getTime());
	}
	
	/**
	 * Check format that is suitable for the next step,
	 * if not, manually modify.
	 * Possible Problem : unexpected format, not covered all cases. 
	 * @param format
	 * @param flag
	 * @return
	 */
	public String checkFormat(String format, int flag) {
		String revisedFormat = format;
		
		if(flag == Constants.DAY_FORMAT) {
			
		}
		else if(flag == Constants.MONTH_FORMAT) {
			
		}
		else if(flag == Constants.YEAR_FORMAT) {
			
		}
		else if(flag == Constants.TIME_FORMAT) {
			String[] SplitFormat = format.split(":");
			if(SplitFormat.length < 3) {
				// e.g, 14:34 <- there's no second data
				// then manually insert :00
				if(SplitFormat.length == 2) {
					revisedFormat += ":00";
				}
				// lastly, just use 00:00:01 format.
				else {
					revisedFormat = "00:00:01";
				}
			}
		}
		
		return revisedFormat;
	}
}
